import 'dart:convert';
import 'AbsBaseBean.dart';
import 'BeanTrans.dart';
import 'JsonClass.dart';


///参考文档：https://www.jianshu.com/p/19df99a86aef    https://www.jianshu.com/p/76adcc3f5541  ffff

@JsonClassBase()
class BaseBean implements AbsBaseBean {
  @override
  void loadJsonString(String json) {
    var map = jsonDecode(json);
    if (map is Map<String, dynamic>) {
      loadJson(map);
    }
  }

  @override
  void loadJson(Map<String, dynamic> jsonmap) {
    MapTransToBeanFunc? func = mapTarnsToBean[getTypeBaseString(this.runtimeType)];
    if (func != null) func(this, jsonmap);
  }

  @override
  Map<String, dynamic> toJson() {
    Map<String, dynamic> map = {};
    beanTransToMap[getTypeBaseString(this.runtimeType)]?.call(this, map);
    return map;
  }

  @override
  String toJsonString() {
    return jsonEncode(toJson());
  }

  @override
  String toString() {
    return toJsonString();
  }

  static init() {
    initMap2();
  }
}

String getTypeBaseString(Type type) {
  var typeName = type.toString();
  var typeArgumentStart = typeName.indexOf("<");
  if (typeArgumentStart > 0) {
    return typeName.substring(0, typeArgumentStart);
  }
  return typeName;
}

extension ListExt on List<BaseBean> {
  List<dynamic> toJson() {
    var list = toValueFromList(this);
    return list;
  }

  String toJsonString() {
    return jsonEncode(toJson());
  }
}

extension MapExt on Map<String, BaseBean> {
  String toJsonString() {
    var map = toValueFromMap(this);
    return jsonEncode(map);
  }
}
